package com.doge.calcalbum.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.doge.calcalbum.core.calcPermissionRequiring
import com.hjq.permissions.XXPermissions

fun checkPermission(permissions: List<String>): Boolean {
    return XXPermissions.isGranted(appContext, permissions)
}


//fun Context.requirePermission(permissions: List<String>, callback: (all: Boolean) -> Unit) {
//    calcPermissionRequiring = true
//    XXPermissions.with(this)
//        .permission(permissions)
//        .request { _, all ->
//            callback(all)
//        }
//}

@RequiresApi(Build.VERSION_CODES.O)
fun Fragment.startInstallPermissionSettingActivity(callback: () -> Unit) {
    calcPermissionRequiring = true
    val uri = Uri.parse("package:${appContext.packageName}")
    val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, uri)
    val startActivityInstall =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            when (result.resultCode) {
                Activity.RESULT_OK -> {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        callback()
                    }
                }
            }
        }
    startActivityInstall.launch(intent)
}